"use client";

import { useState } from "react";
import { Form, Input, Button, Tabs, message } from "antd";
import { MailOutlined, LockOutlined, UserOutlined } from "@ant-design/icons";
import { useRouter } from "next/navigation";
// 导入需要的API函数
import {
  userControllerCreateUser,
  userControllerSendVerification,
} from "@/app/servers/api/user";
import { useAuth } from "@/app/context/AuthContext";
import Image from "next/image";

const { TabPane } = Tabs;

// 添加登录表单的类型定义

interface LoginFormValues {
  email: string;
  password: string;
}

// 添加注册表单的类型定义
interface RegisterFormValues {
  username: string;
  email: string;
  verificationCode: string;
  password: string;
}

export default function LoginPage() {
  const [form] = Form.useForm();
  const [registerForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [activeTab, setActiveTab] = useState("1");
  const router = useRouter();
  const { setIsLoggedIn } = useAuth();

  const validateEmail = (email: string) => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  };

  const handleSendCode = async () => {
    try {
      const email = await registerForm.validateFields(["email"]);
      if (validateEmail(email.email)) {
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);

        // 调用发送验证码API
        await userControllerSendVerification({ email: email.email });
        message.success("验证码已发送");
      }
    } catch {
      message.error("发送验证码失败，请稍后重试");
    }
  };

  const onFinishLogin = async (values: LoginFormValues) => {
    setLoading(true);
    try {
      // 将登录信息存储到 localStorage
      fetch("/customer/login/set-cookie", {
        method: "POST",
        body: JSON.stringify({
          email: values.email,
          password: values.password,
        }),
      }).then(async (res) => {
        if (res.status === 200) {
          const data: API.LoginAuthDto = await res.json();
          localStorage.setItem("token", data.access_token);
          localStorage.setItem("userInfo", JSON.stringify(data));
          setIsLoggedIn(true); // 更新登录状态
          message.success("登录成功");
          router.push("/customer/home");
        } else {
          message.error("登录失败，请检查邮箱和密码");
          setLoading(false);
          throw ('')
        }
      });
    } catch {
      message.error("登录失败，请检查邮箱和密码");
    }
    setLoading(false);
  };

  const onFinishRegister = async (values: RegisterFormValues) => {
    setLoading(true);
    try {
      // 调用注册API
      await userControllerCreateUser({
        email: values.email,
        password: values.password,
        username: values.username,
        verifyCode: values.verificationCode,
      });

      message.success("注册成功，请登录");
      setActiveTab("1");
      form.setFieldsValue({ email: values.email });
      registerForm.resetFields();
    } catch {
      message.error("注册失败，请稍后重试");
    }
    setLoading(false);
  };

  return (
    <div
      className=" flex items-center justify-center bg-gradient-to-br py-12 px-4 sm:px-6 lg:px-8"
      style={{
        height: "calc(100vh - 81px - 112px)",
      }}
    >
      <Image
        src="/bg.png"
        alt="背景"
        sizes="100vw"
        width={0}
        height={0}
        className="absolute"
        style={{
          height: "calc(100vh - 81px - 112px)",
          width: "100%",
        }}
      />
      <div className="relative max-w-md w-full space-y-8 bg-gradient-to-br bg-white border-gray border-solid border-2  p-8 rounded-lg shadow-md">
        <Tabs activeKey={activeTab} onChange={setActiveTab} centered>
          <TabPane tab="登录" key="1">
            <Form
              form={form}
              name="login"
              onFinish={onFinishLogin}
              className="mt-8 space-y-6"
            >
              <Form.Item
                name="email"
                rules={[
                  { required: true, message: "请输入邮箱" },
                  { type: "email", message: "请输入有效的邮箱地址" },
                ]}
              >
                <Input prefix={<MailOutlined />} placeholder="邮箱" />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password prefix={<LockOutlined />} placeholder="密码" />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                >
                  登录
                </Button>
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="注册" key="2">
            <Form
              form={registerForm}
              name="register"
              onFinish={onFinishRegister}
              className="mt-8 space-y-6"
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: "请输入用户名" },
                  { max: 20, message: "用户名最多20个字符" },
                ]}
              >
                <Input prefix={<UserOutlined />} placeholder="用户名" />
              </Form.Item>

              <Form.Item
                name="email"
                rules={[
                  { required: true, message: "请输入邮箱" },
                  { type: "email", message: "请输入有效的邮箱地址" },
                ]}
              >
                <Input prefix={<MailOutlined />} placeholder="邮箱" />
              </Form.Item>

              <Form.Item
                name="verificationCode"
                rules={[{ required: true, message: "请输入验证码" }]}
              >
                <div className="flex gap-4">
                  <Input placeholder="验证码" />
                  <Button onClick={handleSendCode} disabled={countdown > 0}>
                    {countdown > 0 ? `${countdown}s` : "发送验证码"}
                  </Button>
                </div>
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password prefix={<LockOutlined />} placeholder="密码" />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                >
                  注册
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </div>
    </div>
  );
}
